package service

import (
	"aigen-todo/internal/interfaces"
	"aigen-todo/internal/models"
	"time"
)

type TaskService struct {
	taskRepo      interfaces.TaskRepositoryInterface
	taskGroupRepo interfaces.TaskGroupRepositoryInterface
	userRepo      interfaces.UserRepositoryInterface
}

func NewTaskService(taskRepo interfaces.TaskRepositoryInterface, taskGroupRepo interfaces.TaskGroupRepositoryInterface, userRepo interfaces.UserRepositoryInterface) *TaskService {
	return &TaskService{
		taskRepo:      taskRepo,
		taskGroupRepo: taskGroupRepo,
		userRepo:      userRepo,
	}
}

func (s *TaskService) CreateTask(userID, groupID uint64, title, description string, isImportant, isMyDay bool, dueDate *time.Time) (*models.Task, error) {
	// 检查用户是否存在
	_, err := s.userRepo.GetByID(userID)
	if err != nil {
		return nil, err
	}

	// 检查任务分组是否存在
	_, err = s.taskGroupRepo.GetByID(groupID)
	if err != nil {
		return nil, err
	}

	// 创建任务
	task := &models.Task{
		UserID:      userID,
		GroupID:     groupID,
		Title:       title,
		Description: description,
		IsImportant: isImportant,
		IsMyDay:     isMyDay,
		DueDate:     dueDate,
	}

	err = s.taskRepo.Create(task)
	if err != nil {
		return nil, err
	}

	return task, nil
}

func (s *TaskService) GetTaskByID(id uint64) (*models.Task, error) {
	return s.taskRepo.GetByID(id)
}

func (s *TaskService) GetTasksByUserID(userID uint64) ([]models.Task, error) {
	return s.taskRepo.GetByUserID(userID)
}

func (s *TaskService) GetTasksByGroupID(groupID uint64) ([]models.Task, error) {
	return s.taskRepo.GetByGroupID(groupID)
}

func (s *TaskService) GetMyDayTasks(userID uint64) ([]models.Task, error) {
	return s.taskRepo.GetMyDayTasks(userID)
}

func (s *TaskService) UpdateTask(task *models.Task) error {
	task.UpdatedAt = time.Now()
	return s.taskRepo.Update(task)
}

func (s *TaskService) DeleteTask(id uint64) error {
	return s.taskRepo.Delete(id)
}

func (s *TaskService) ChangeTaskGroup(taskID, groupID uint64) error {
	// 检查任务是否存在
	_, err := s.taskRepo.GetByID(taskID)
	if err != nil {
		return err
	}

	// 检查任务分组是否存在
	_, err = s.taskGroupRepo.GetByID(groupID)
	if err != nil {
		return err
	}

	return s.taskRepo.ChangeGroup(taskID, groupID)
}
